package com.onec.service.im.codec;

import com.onec.service.im.protocol.Common;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToByteEncoder;

import java.util.List;

public class ProtoDecode extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

        // 标记读指针的位置
        in.markReaderIndex();
        if (in.readableBytes() < 2) {
            return;
        }
        int length = in.readShort();
        if (length < 0) {
            ctx.close();
        }
        if (length > in.readableBytes()) {
            in.resetReaderIndex();
            return;
        }

        // 读取魔数 版本 内容
        byte[] arary;
        if (in.hasArray()) {
            ByteBuf byteBuf = in.slice();
            arary = byteBuf.array();
        } else {
            arary = new byte[length];
            in.readBytes(arary, 0, length);
        }

        // 转成对象
        Common.Point c = Common.Point.parseFrom(arary);
        if (c != null) {
            out.add(c);
        }

    }
}
